package com.wufeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.constant.CachePrefix;
import com.wufeng.dto.R;
import com.wufeng.dto.UserDto;
import com.wufeng.entity.User;
import com.wufeng.service.UserService;
import com.wufeng.service.cache.CacheService;
import com.wufeng.utils.JwtUtils;
import com.wufeng.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private CacheService cacheService;


    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R userLogin(@RequestBody User user, HttpSession httpSession) {

        //生成token
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("username", user.getUsername());
        hashMap.put("password", user.getPassword());
        String token = JwtUtils.createToken(hashMap);


        User role = null;
        Map<String, Object> map = new HashMap<>();

        if (user.getUserrole() == 1) {//大学生登录
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>().
                    eq("userName", user.getUsername()).
                    eq("passWord", user.getPassword()).
                    eq("userRole", 1);
            role = userService.getOne(queryWrapper);

            if (role == null) {//用户名或密码错误
                map.put("login", false);
                map.put("msg", "用户名或密码错误");
                return R.ok(map);
            }
            if (role.getUserstatus() != 1) {//账户已锁定
                map.put("login", false);
                map.put("msg", "账户已锁定");

            } else {//允许登录
                map.put("login", true);
                map.put("msg", "登陆成功");
                map.put("user", role);
                map.put("token", token);
            }
        } else if (user.getUserrole() == 2) {//咨询师登录
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>().
                    eq("userName", user.getUsername()).
                    eq("passWord", user.getPassword()).
                    eq("userRole", 2);
            role = userService.getOne(queryWrapper);

            if (role == null) {//用户名或密码错误
                map.put("login", false);
                map.put("msg", "用户名或密码错误");
                return R.ok(map);
            }
            if (role.getUserstatus() != 1) {//账户已锁定
                map.put("login", false);
                map.put("msg", "账户已锁定");

            } else {//允许登录
                map.put("login", true);
                map.put("msg", "登陆成功");
                map.put("user", role);
                map.put("token", token);
            }

        } else if (user.getUserrole() == 3) {//管理员登录
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>().
                    eq("userName", user.getUsername()).
                    eq("passWord", user.getPassword()).
                    eq("userRole", 3);
            role = userService.getOne(queryWrapper);

            if (role == null) {//用户名或密码错误
                map.put("login", false);
                map.put("msg", "用户名或密码错误");
                return R.ok(map);
            }
            if (role.getUserstatus() != 1) {//账户已锁定
                map.put("login", false);
                map.put("msg", "账户已锁定");

            } else {//允许登录
                map.put("login", true);
                map.put("msg", "登陆成功");
                map.put("user", role);
                map.put("token", token);
            }
        } else {
            return R.error(401, "角色错误");
        }
        return R.ok(map);
    }

    /**
     * 根据id获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfoById")
    public R getUserInfoById(@RequestParam Integer userId) {
        User user = userService.getOne(new QueryWrapper<User>().eq("userId", userId));
        Map<String, Object> map = new HashMap<>();
        if (user != null) {
            user.setPassword("");
        }
        map.put("user", user);
        return R.ok(map);
    }

    /**
     * 根据根据用户iD更新用户头像
     *
     * @param user 只需两个成员变量即可
     * @return
     */
    @PostMapping("/updateAvatarByUserId")
    public R updateAvatarByUserId(@RequestBody User user) {

        user.setUpdatetime(new Date());
        Boolean isUpdate = userService.updateAvatarByUserId(user);
        Map<String, Object> map = new HashMap<>();
        map.put("isUpdate", isUpdate);
        return R.ok(map);
    }


    /**
     * 根据根据用户iD更新用户数据
     *
     * @param user
     * @return
     */
    @PostMapping("/updateUserByUserId")
    public R updateUserByUserId(@RequestBody User user) {

        boolean isUpdate = userService.update(user, new QueryWrapper<User>().eq("userId", user.getUserid()));
        Map<String, Object> map = new HashMap<>();
        map.put("isUpdate", isUpdate);
        return R.ok(map);
    }

    /**
     * 检查密码是否正确
     *
     * @param user
     * @return
     */
    @PostMapping("/checkPassWord")
    public R checkPassWord(@RequestBody User user) {

        User one = userService.getOne(
                new QueryWrapper<User>().eq("userId", user.getUserid()).eq("passWord", user.getPassword())
        );
        Map<String, Object> map = new HashMap<>();
        map.put("isLegal", one == null ? false : true);
        return R.ok(map);
    }


    //更新密码
    @PostMapping("/updatePassWord")
    public R updatePassWord() {
        return R.ok();
    }

    /**
     * 检查用户名是否存在
     *
     * @param userName
     * @return
     */
    @GetMapping("/isExistUserName")
    public R isExistUserName(@RequestParam("username") String userName) {
        List<User> list = userService.list(new QueryWrapper<User>().eq("userName", userName));
        HashMap<String, Object> map = new HashMap<>();
        map.put("isExist", list.isEmpty() ? false : true);
        return R.ok(map);
    }

    /**
     * 检查号码是否已经存在
     *
     * @param phoneNumber
     * @return
     */
    @GetMapping("/isExistPhoneNumber")
    public R isExistPhoneNumber(@RequestParam("phonenumber") String phoneNumber) {
        List<User> list = userService.list(new QueryWrapper<User>().eq("phoneNumber", phoneNumber));
        HashMap<String, Object> map = new HashMap<>();
        map.put("isExist", list.isEmpty() ? false : true);
        return R.ok(map);
    }


    /**
     * 用户注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody UserDto userDto) {
        System.out.println("接收的:" + userDto);

        //从redis拿到验证码对比
        String code = cacheService.get(CachePrefix.REGISTER.getPrefix() + userDto.getPhonenumber());
        System.out.println("userDto验证码:" + userDto.getVerificationCode());
        System.out.println("验证码:" + StringUtils.removeQuotes(code));
        if (code == null || userDto.getVerificationCode() == null || !StringUtils.removeQuotes(code).equals(userDto.getVerificationCode())) {
            return R.error("验证码错误");
        }
        //检查用户名是否存在
        User user = userService.getOne(new QueryWrapper<User>().eq("userName", userDto.getUsername()));
        if (user != null) {
            return R.error("用户名已存在");
        }

        //存入数据库
        User one = new User();
        BeanUtils.copyProperties(userDto, one);
        one.setCreatetime(new Date());
        one.setUpdatetime(new Date());
        one.setUserrole(1);
        one.setUserstatus(1);
        System.out.println("存放的:" + one);
        boolean isSaved = userService.save(one);

        HashMap<String, Object> map = new HashMap<>();
        map.put("isSaved", isSaved);

        return R.ok(map);
    }


    /**
     * 根据手机号修改用户密码
     *
     * @param user
     * @return
     */
    @PostMapping("/updatePassWordByPhoneNumber")
    @Transactional
    public R updatePassWordByPhoneNumber(@RequestBody User user) {

        System.out.println(user);
        boolean isUpdate = userService.update(user, new QueryWrapper<User>().eq("phoneNumber", user.getPhonenumber()));

        HashMap<String, Object> map = new HashMap<>();
        map.put("isUpdate", isUpdate);
        return R.ok(map);
    }

    /**
     * 根据用户id获取经过处理的手机号
     *
     * @param userId
     * @return
     */
    @GetMapping("/getPhoneNumberByUserId")
    public R getPhoneNumberByUserId(@RequestParam("userId") Integer userId) {

        User user = userService.getOne(new QueryWrapper<User>().eq("userId", userId));
        HashMap<String, Object> map = new HashMap<>();
        if (user == null || user.getPhonenumber() == null || user.getPhonenumber().length() != 11) {
            map.put("phoneNumber", "");
            return R.ok(map);
        }

        String number = user.getPhonenumber();
        String phoneNumber = number.substring(0, 3) + "****" + number.substring(7, 11);
        map.put("phoneNumber", phoneNumber);
        return R.ok(map);
    }

    /**
     * 判断手机号是否已经被绑定
     *
     * @param phoneNumber
     * @return
     */
    @GetMapping("/phoneNumberIsAlreadyBind")
    public R phoneNumberIsAlreadyBind(@RequestParam("phoneNumber") String phoneNumber) {
        List<User> list = userService.list(new QueryWrapper<User>().eq("phoneNumber", phoneNumber));

        if (!list.isEmpty()) {
            return R.error("该手机号已被其他用户绑定");
        }
        return R.ok();
    }

    /**
     * 根据用户id修改手机号
     *
     * @param user
     * @return
     */
    @PostMapping("/updatePhoneNumberByUserId")
    public R updatePhoneNumberByUserId(@RequestBody User user) {
        System.out.println(user);
        if (user == null || user.getUserid() == null || user.getPhonenumber() == null || user.getPhonenumber().length() != 11) {
            return R.error("请求参数有误");
        }
        userService.updateById(user);
        return R.ok();
    }


    /**
     * 根据用户角色获取用户列表
     *
     * @return
     */
    @GetMapping("/getAllUserByRole")
    public R getAllUserByRole(@RequestParam("userrole") Integer userrole) {

        if (userrole == null) {
            return R.error("请求参数有误");
        }
        List<User> userList = userService.list(new QueryWrapper<User>().eq("userRole", userrole));

        List<User> consultants = userList.stream().map(user -> {
            user.setPassword("");
            return user;
        }).collect(Collectors.toList());

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", consultants);
        return R.ok(map);
    }


    /**
     * 根据条件查询用户列表
     *
     * @param params
     * @return
     */
    @PostMapping("/getUserListByConditions")
    public R getUserListByConditions(@RequestBody Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageIndex == null || pageSize == null) {
            pageIndex = 1;
            pageSize = 5;
        }

        User user = new User();
        user.setUsername((String) params.get("username"));
        user.setPhonenumber((String) params.get("phonenumber"));

        List<User> userList = userService.getUserListByConditions(user, pageIndex, pageSize);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userList", userList);
        return R.ok(map);

    }

    /**
     * 获取账号总数量
     *
     * @return
     */
    @PostMapping("/getTotalUserCount")
    public R getTotalUserCount(@RequestBody User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if(user.getUsername()!=null&&!user.getUsername().equals("")){
            qw.like("userName",user.getUsername());
        }
        if(user.getPhonenumber()!=null&&!user.getPhonenumber().equals("")){
            qw.like("phoneNumber",user.getPhonenumber());
        }
        long count = userService.count(qw);
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", count);
        return R.ok(map);
    }

    /**
     * 根据id修改用户状态
     *
     * @param userId
     * @param userStatus
     * @return
     */
    @PostMapping("/changeUserStatusById")
    public R changeUserStatusById(@RequestParam("userid") Integer userId,
                                  @RequestParam("userstatus") Integer userStatus) {

        User user = new User();
        user.setUserid(userId);
        user.setUserstatus(userStatus);
        user.setUpdatetime(new Date());

        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.updateById(user);
        } catch (Exception e) {
            return R.error("修改失败");
        }

        return R.ok("修改成功");
    }

    /**
     * 根据id修改用户的身份
     *
     * @param userId
     * @param userRole
     * @return
     */
    @PostMapping("/changeUserRoleById")
    public R changeUserRoleById(@RequestParam("userid") Integer userId,
                                @RequestParam("userrole") Integer userRole) {

        User user = new User();
        user.setUserid(userId);
        user.setUserrole(userRole);
        user.setUpdatetime(new Date());

        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.updateById(user);
        } catch (Exception e) {
            return R.error("修改失败");
        }

        return R.ok("修改成功");
    }


    /**
     * 根据id删除用户
     *
     * @param user
     * @return
     */
    @PostMapping("/deleteUserById")
    public R deleteUserById(@RequestBody User user) {
        try {
            userService.removeById(user.getUserid());
        } catch (Exception e) {
            return R.error("删除失败！");
        }
        return R.ok("删除成功！");
    }

    /**
     * 根据用户量模糊查询获取用户列表
     * @param userName
     * @return
     */
    @GetMapping("/getUserIdsByUserName")
    public R getUserIdsByUserName(@RequestParam("userName") String userName){
        List<Integer> ids = userService.getUserIdsByUserName(userName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("ids",ids);
        return R.ok(map);
    }


}
